﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ReceiptTracker
{
    public partial class FormAddShop : Form
    {
        private SQLiteDB db;
        private List<Category> categoryList = new List<Category>();
        public FormAddShop(SQLiteDB db)
        {
            InitializeComponent();
            this.db = db;
            //Initialize shop list
            this.categoryList.Clear();
            db.SQLQuery("SELECT * FROM Categories;");
            foreach (DataRow row in db.QueryResult.Rows)
            {
                categoryList.Add(new Category(Convert.ToInt32(row["id"]), row["name"].ToString()));
            }
            comboBoxCategory.DataSource = categoryList;
            comboBoxCategory.ValueMember = "name";
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            Regex rgx = new Regex(@"^[a-öA-Ö`\s]*$");
            if (comboBoxCategory.SelectedIndex == -1)
            {
                MessageBox.Show("Can't add a shop without a category", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);   
            }
            else if (!rgx.IsMatch(textBoxName.Text))
            {
                MessageBox.Show("Invalid characters in shop name\nValid characters are a-ö, A-Ö and `", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                db.SQLCommand("INSERT INTO Shops (name,category) VALUES ('" + textBoxName.Text + "', " + categoryList[comboBoxCategory.SelectedIndex].Id + ");");
                this.DialogResult = DialogResult.OK;    
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }
    }
}
